package com.rainszj.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常异常处理器
 * @author rainszj
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public String exceptionHandler(HttpServletRequest request, Exception e, Model model) throws Exception {
        // 日志，控制台记录错误信息
        logger.error("Request URL : {}, Exception: {}", request.getRequestURL(), e);

        /*将找不到资源异常交给springboot来处理，ControllerAdvice不拦截*/
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        // 将错误信息携带给前端
        model.addAttribute("url", request.getRequestURL());
        model.addAttribute("exception", e);

        return "error/error";
    }


}
